const CONFIG = require('./base_config.js').config;
const wsAPI = require('./utils/wx_api.js').wsAPI;
const queryHelper = require('./utils/request_helper/request_helper.js');
const Promise = require('./utils/promise.js');

App({

    globalData: {
        userInfo: null,
        historyList: null, // 浏览历史列表，从缓存中获取后挂载到全局对象中避免重复调用getStorage
        wsAPI: wsAPI, // 将wxAPI挂载到全局对象对象中以便其它页面可以直接使用
        config: CONFIG,
        promise: Promise,
        imgUrl: CONFIG.imgUrl
    },

    appData: {
        code: null
    },

    onLaunch: function (options) {
        this.initOptions(options);
        this.initStorage();
        this.initCookieId();
        this.getSysInfo();
        this.handleGetUserInfo();
    },

    // 通过外部传经来的参数~初始化对应的变量
    initOptions: function (options) {
    },

    // 初始化缓存数据
    initStorage: function() {
        this.globalData.historyList = wx.getStorageSync('HISTORY_LIST');
    },

    // 生成或获取已经缓存的cookieid
    initCookieId: function () {
        try {
            let cookieId = wx.getStorageSync('COOKIE_ID');
            if (!cookieId) {
                cookieId = new Date().getTime();
                wx.setStorageSync('COOKIE_ID', cookieId);
            }
            this.globalData.cookieId = cookieId;
        } catch (e) { }
    },

    // 获取系统信息区别处理样式
    getSysInfo: function () {
        try {
            let systemInfoArr = wx.getSystemInfoSync().system.split(' ');
            this.globalData.sysType = this.appData.sysType = systemInfoArr[0].toUpperCase();
        } catch (e) { }
    },

    handleGetUserInfo: function () {
        this.globalData.userInfoPromise = new Promise((resolve, reject) => {

            try {
                const userInfo = wx.getStorageSync('USER_INFO');
                if (userInfo) {
                    this.globalData.userInfo = userInfo;
                    resolve(userInfo);
                } else {
                    // 登录
                    wx.login({
                        success: res => {
                            this.appData.code = res.code;
                            // 获取用户信息
                            wx.getSetting({
                                success: res => {
                                    this.getUserInfo();
                                }
                            })
                        }
                    })
                }
            } catch (e) { }
        })
    },

    getUserInfo: function () {
        console.log('调用了请求用户信息接口');
        let userInfo = null;
        wsAPI.getUserInfo()
            .then((res) => {
                res.userInfo.code = this.appData.code;
                userInfo = res.userInfo;

                const bodyData = {
                    encryptedData: res.encryptedData,
                    iv: res.iv,
                    code: this.appData.code
                };
                return this.wxRequest({
                    interfaceName: CONFIG.interfaceList.LOGIN,
                    reqData: {
                        parentUserCode: ' '
                    },
                    bodyData: bodyData,
                    extendsOptions: {
                        method: 'POST'
                    }
                })
            }, (res) => {
                wx.openSetting({
                    success: () => {
                        this.getUserInfo();
                    },
                    fail: (res) => {
                        console.log(res);
                    }
                })
            })
            .then((res) => {
                return this.wxRequest({
                    interfaceName: CONFIG.interfaceList.GETUSERINFO,
                    reqData: {
                        userId: res.data
                    }
                })
            })
            .then((res) => {
                userInfo = {
                    ...userInfo,
                    ...res.data
                };

                this.globalData.userInfo = userInfo;
                wx.setStorage({
                    key: 'USER_INFO',
                    data: userInfo
                });
            })
            
    },

    wxRequest: function ({
		interfaceName,
        reqData,
        bodyData,
        failCb = (res) => {
            console.log('请求失败~具体信息为：', res);
            wx.showToast({
                title: res.msg.length > 7 ? '接口请求错误' : res.msg,
                image: '/images/common/err_tip_icon.png',
                duration: 2000
            })
        },
        isShowLoad = 1,
        extendsOptions = {}
	}) {
        if (isShowLoad === 1) {
            wx.showLoading({
                title: '加载中...',
            });
        }

        const domin = CONFIG.interfaceDomin;
        const reqUrl = reqData ?
            `${domin}${interfaceName}/${queryHelper.queryEncoded(reqData)}` :
            `${domin}${interfaceName}`;

        console.log('请求信息：', reqUrl, reqData);

        return wsAPI.request({
            url: reqUrl,
            data: bodyData || '',
            method: extendsOptions.method || CONFIG.reqMethod,
            header: {
                ...CONFIG.header,
                cookie_id: this.appData.cookieId
            }
        }).then((res) => {
            wx.hideLoading();
            if (res.data.code !== '1') {
                failCb(res.data);
            }
            return res.data;

        }, (res) => {
            wx.hideLoading();
            failCb(res.data);
            return res;
        })
    },
})